<template>
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span prefix-icon="el-icon-arrow-left">发表文章</span>
            <el-link type="primary" @click="$router.push('/art-list')" style="float: right;font-size:small;">＜返回
            </el-link>
        </div>
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
            <el-form-item label="文章标题" prop="title">
                <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id">
                <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
                    <el-option :label="item.cate_name" :value="item.id" v-for="(item, index) in cateList"
                        :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="文章内容" prop="content" @blur="refs.pubFormRef.validateField('content')">
                <quill-editor v-model="pubForm.content"></quill-editor>
            </el-form-item>
            <el-form-item label="文章封面" prop="cover_img">
                <!-- 用来显示封面的图片 -->
                <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
                <br />
                <!-- 文件选择框，默认被隐藏 -->
                <input type="file" style="display: none" ref="inputRef" @change="changeImg" />
                <!-- 选择封面的按钮 -->
                <el-button type="primary" plain @click="chooseImg" class="choose">+ 选择封面</el-button> <br>
            </el-form-item>
            <el-form-item style="margin-top: 30px;">
                <el-button type="primary" @click="add('已发布')">发布</el-button>
                <el-button type="info" @click="add('草稿')">存为草稿</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
import defaultImg from '@/assets/images/cover.jpg'
export default {
    name: 'VueCmsArtAdd',
    data() {
        return {
            cateList: [],
            pubForm: {
                title: '',
                cate_id: '',
                content: '',
                cover_img: null,
                state: ''
            },
            pubFormRules: {
                title: [
                    { required: true, message: '请输入文章标题', trigger: 'blur' },
                    { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
                ],
                cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
                content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
                cover_img: [{ required: true, message: '请选择图片', trigger: 'change' }],
            },
        };
    },

    mounted() {

    },

    methods: {
        async initCateList() {
            const { data: res } = await this.$http.get('/my/cate/list')
            if (res.code == 0) this.cateList = res.data
        },
        chooseImg() {
            this.$refs.inputRef.click();
        },
        changeImg(e) {
            // console.log(e.target.files);
            // base 64
            // const files = e.target.files;
            // if (files.length == 0) {
            //     this.pubForm.cover_img = "";
            // } else {
            //     const fr = new FileReader();
            //     fr.readAsDataURL(files[0]);
            //     fr.onload = (e) => {
            //         this.pubForm.cover_img = e.target.result;
            //     };
            // }
            const files = e.target.files
            if (files.length === 0) {
                // 用户没有选择封面
                this.pubForm.cover_img = null
                this.$refs.imgRef.setAttribute('src', defaultImg)
            } else {
                // 用户选择了封面
                this.pubForm.cover_img = files[0]
                const url = URL.createObjectURL(files[0])
                this.$refs.imgRef.setAttribute('src', url)
            }
            this.$refs.pubFormRef.validateField('cover_img')
        },
        add(state) {
            this.pubForm.state = state
            this.$refs.pubFormRef.validate(async valid => {
                if (!valid) return
                if (!this.pubForm.content) return this.$message.error('请输入内容')
                if (!this.pubForm.cover_img) return this.$message.error('请选择封面')



                // console.log(this.pubForm);
                // let fd = new FormData()
                // console.log(fd);
                // const arr = Object.keys(this.pubForm)
                // console.log(arr);
                // arr.forEach(item => {
                //     fd.append(item, this.pubForm.item)
                // })
                // console.log(fd);
                // console.log(this.pubForm.cover_img);
                const fd = new FormData()
                // fd.append(hai,123)
                // console.log(fd);
                // 2. 向 FormData 中追加数据
                Object.keys(this.pubForm).forEach(item => {
                    // console.log(item,this.pubForm[item]);
                    fd.append(item, this.pubForm[item])
                })
                // 3. 发起请求
                const { data: res } = await this.$http.post('/my/article/add', fd)
                if (res.code !== 0) return this.$message.error(res.message)
                this.$message.success('发布文章成功！')
                this.$router.push('/art-list');
            })
        }
    },
    created() {
        this.initCateList()
    },
};
</script>

<style lang="less" scoped>
/deep/ .ql-editor {
    min-height: 300px;
}

.cover-img {
    width: 500px;
    height: 350px;
    object-fit: cover;
}

</style>